package com.uinnova.product.eam.workable.listener;

import com.uinnova.product.eam.workable.model.ActRuTask;
import com.uinnova.product.eam.workable.repository.ActRuTaskRepository;
import lombok.extern.slf4j.Slf4j;
import org.flowable.common.engine.impl.db.SuspensionState;
import org.flowable.engine.TaskService;
import org.flowable.engine.delegate.TaskListener;
import org.flowable.task.service.delegate.DelegateTask;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Optional;

/**
 * 子流程任务挂起监听器，子流程中多个实例驳回审批回将后续审批任务执行完后将任务挂起
 *
 * @author lichong
 * @since 2024/7/22 上午10:34
 */
@Slf4j
@Service("suspensionTaskListener")
public class SuspensionTaskListener implements TaskListener {


    @Resource
    private ActRuTaskRepository actRuTaskRepository;

    @Resource
    private TaskService taskService;


    @Override
    public void notify(DelegateTask delegateTask) {
        String taskDefinitionKey = delegateTask.getTaskDefinitionKey();
        String processInstanceId = delegateTask.getProcessInstanceId();
        String assignee = delegateTask.getAssignee();
        if("$INITIATOR".equalsIgnoreCase(assignee)){
            return;
        }
        long count = taskService.createTaskQuery().taskDefinitionKey(taskDefinitionKey)
                .processInstanceId(processInstanceId).taskAssignee(assignee).count();
        if (count > 0) {
            Optional<ActRuTask> currentTask = actRuTaskRepository.findById(delegateTask.getId());
            if (currentTask.isPresent()) {
                ActRuTask actRuTask = currentTask.get();
                actRuTask.setSuspensionState(SuspensionState.SUSPENDED.getStateCode());
                actRuTaskRepository.saveAndFlush(actRuTask);
            }
        }
    }
}
